import React, {useState, useEffect} from 'react';
import {
    Table,
    Card,
    Button,
    Tag,
    Space,
    Modal,
    Descriptions,
    message,
    Input,
    Select,
    Progress,
    Divider,
    Avatar,
    Popover,
    Skeleton,
    Pagination,
    List,
    Form,
    Rate
} from 'antd';
import {
    DownloadOutlined,
    EyeOutlined,
    SearchOutlined,
    UserOutlined,
    StarOutlined,
    StarFilled,
    LikeOutlined,
    DislikeOutlined,
    DeleteOutlined,
    CommentOutlined
} from '@ant-design/icons';
import {useDispatch} from 'react-redux';
import {
    fetchTorrentList,
    fetchUserProfile,
    followUser,
    deFollowUser,
    downloadTorrent,
    fetchComments,
    addComment,
    likeComment,
    deleteComment
} from '../../store/modules/userStore';
import './torrentList.css';

const {TextArea} = Input;
const {Option} = Select;

const TorrentList = () => {
    const dispatch = useDispatch();
    const [data, setData] = useState({list: [], total: 0});
    const [loading, setLoading] = useState(false);
    const [selectedTorrent, setSelectedTorrent] = useState(null);
    const [uploaderInfo, setUploaderInfo] = useState(null);
    const [uploaderLoading, setUploaderLoading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [searchParams, setSearchParams] = useState({
        id: '',
        page: 1,
        size: 10
    });
    const [commentList, setCommentList] = useState({list: [], total: 0});
    const [commentLoading, setCommentLoading] = useState(false);
    const [commentPage, setCommentPage] = useState(1);
    const [commentContent, setCommentContent] = useState('');
    const currentUserId = localStorage.getItem('userId');
    const passKey = localStorage.getItem('passKey');

    // 分类选项
    const categories = [
        {id: 1, name: '电影'},
        {id: 2, name: '电视剧'},
        {id: 3, name: '音乐'},
        {id: 4, name: '游戏'},
        {id: 5, name: '软件'}
    ];

    // 获取种子列表
    const fetchData = () => {
        setLoading(true);
        dispatch(fetchTorrentList(searchParams))
            .then(res => {
                if (res && res.code === 0) {
                    setData(res.data || {list: [], total: 0});
                } else {
                    message.error(res?.msg || '获取种子列表失败');
                }
            })
            .catch(err => {
                console.error('获取种子列表错误:', err);
                message.error('获取种子列表出错');
            })
            .finally(() => {
                setLoading(false);
            });
    };

    // 获取上传者信息
    const fetchUploaderInfo = (userId) => {
        setUploaderLoading(true);
        dispatch(fetchUserProfile(userId))
            .then(res => {
                if (res && res.code === 0) {
                    setUploaderInfo(res.data);
                } else {
                    message.error(res?.msg || '获取用户信息失败');
                }
            })
            .catch(err => {
                console.error('获取用户信息错误:', err);
                message.error('获取用户信息出错');
            })
            .finally(() => {
                setUploaderLoading(false);
            });
    };

    // 处理关注/取消关注用户
    const handleFollow = async (userId, followed) => {
        try {
            const action = followed ? deFollowUser : followUser;
            const res = await dispatch(action(userId));

            if (res.code === 0) {
                const msg = res.data;
                message.success(msg);
                setUploaderInfo(prev => ({
                    ...prev,
                    followed: !followed
                }));
            } else {
                const msg = res.msg;
                message.warning(msg);
            }
        } catch (err) {
            console.error('操作错误:', err);
            message.error('网络请求失败，请稍后重试');
        }
    };

    // 获取评论列表
    const fetchCommentsList = async () => {
        if (!selectedTorrent) return;

        const requestData = {
            page: commentPage,
            size: 5,
            torrentId: selectedTorrent.id
        };

        setCommentLoading(true);
        try {
            const res = await dispatch(fetchComments(requestData));
            if (res && res.code === 0) {
                setCommentList({
                    list: res.data.list || [],
                    total: res.data.total || 0
                });
                console.log("commentList: ",commentList)
            } else {
                message.error(res?.msg || '获取评论列表失败');
            }
        } catch (err) {
            console.error('请求失败:', err);
            message.error('获取评论列表出错');
        } finally {
            setCommentLoading(false);
        }
    };

    // 提交评论
    const handleCommentSubmit = () => {
        if (!selectedTorrent) return;
        if (!commentContent.trim()) {
            message.warning('评论内容不能为空');
            return;
        }

        dispatch(addComment({
            torrentId: selectedTorrent.id,
            userId: currentUserId,
            content: commentContent,
            isAnonymous: false
        }))
            .then(res => {
                if (res && res.code === 0) {
                    message.success('评论提交成功');
                    setCommentContent('');
                    // 刷新评论列表
                    fetchCommentsList();
                } else {
                    message.error(res?.msg || '提交评论失败');
                }
            })
            .catch(err => {
                console.error('提交评论错误:', err);
                message.error('提交评论出错');
            });
    };

    // 点赞评论
    const handleLikeComment = (commentId) => {
        dispatch(likeComment({id: commentId}))
            .then(res => {
                if (res && res.code === 0) {
                    // 更新评论列表中的点赞数
                    setCommentList(prev => ({
                        ...prev,
                        list: prev.list.map(comment =>
                            comment.id === commentId ?
                                {...comment, likes: comment.likes + 1} :
                                comment
                        )
                    }));
                } else {
                    message.error(res?.msg || '点赞失败');
                }
            })
            .catch(err => {
                console.error('点赞评论错误:', err);
                message.error('点赞评论出错');
            });
    };

    // 删除评论
    const handleDeleteComment = (commentId) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这条评论吗？',
            onOk: () => {
                dispatch(deleteComment({id: commentId}))
                    .then(res => {
                        if (res && res.code === 0) {
                            message.success('评论删除成功');
                            // 刷新评论列表
                            fetchCommentsList();
                        } else {
                            message.error(res?.msg || '删除评论失败');
                        }
                    })
                    .catch(err => {
                        console.error('删除评论错误:', err);
                        message.error('删除评论出错');
                    });
            }
        });
    };

    // 处理评论分页变化
    const handleCommentPageChange = (page) => {
        setCommentPage(page);
    };

    useEffect(() => {
        fetchData();
    }, [searchParams]);

    // 当选中种子或评论页码变化时获取评论
    useEffect(() => {
        fetchCommentsList();
    }, [selectedTorrent, commentPage]);

    // 格式化文件大小
    const formatSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // 处理下载
    const handleDownload = async (torrentId) => {
        try {
            const res = await dispatch(downloadTorrent({
                id: torrentId,
                passKey: passKey
            }));

            if (res.code === 0) {
                const downloadUrl = res.data;
                // 创建隐藏的a标签触发下载
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.download = '';
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                message.success('开始下载种子文件');
            } else {
                message.error(res.msg || '下载失败');
            }
        } catch (err) {
            console.error('下载错误:', err);
            message.error('下载失败');
        }
    };

    // 显示详情
    const showDetail = (record) => {
        setSelectedTorrent(record);
        if (!record.anonymous && record.userId) {
            fetchUploaderInfo(record.userId);
        }
        setIsModalVisible(true);
        setCommentPage(1); // 重置评论页码
    };

    // 处理分页变化
    const handlePageChange = (page, size) => {
        setSearchParams(prev => ({
            ...prev,
            page,
            size
        }));
    };

    // 处理搜索
    const handleSearch = () => {
        setSearchParams(prev => ({
            ...prev,
            page: 1 // 搜索时重置到第一页
        }));
    };

    // 重置搜索
    const handleReset = () => {
        setSearchParams({
            id: '',
            page: 1,
            size: 10
        });
    };

    // 表格列定义
    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <div className="torrent-title">
                    <span>{text}</span>
                    {record.freeleech && (
                        <Tag color="green" style={{marginLeft: 8}}>免费</Tag>
                    )}
                </div>
            ),
        },
        {
            title: '上传者',
            dataIndex: 'userName',
            key: 'uploader',
            width: 150,
            render: (text, record) => (
                record.anonymous ? (
                    <Tag>匿名</Tag>
                ) : (
                    <Popover
                        content={
                            <div style={{padding: 8}}>
                                <Skeleton loading={uploaderLoading} active>
                                    {uploaderInfo && (
                                        <div>
                                            <p>用户名: {uploaderInfo.username}</p>
                                            <p>等级: Lv.{uploaderInfo.level}</p>
                                        </div>
                                    )}
                                </Skeleton>
                            </div>
                        }
                        trigger="hover"
                    >
                        <Tag icon={<UserOutlined/>}>{text || `用户 ${record.uploaderId}`}</Tag>
                    </Popover>
                )
            ),
        },
        {
            title: '大小',
            dataIndex: 'fileSize',
            key: 'fileSize',
            width: 120,
            render: (size) => formatSize(size),
            sorter: (a, b) => a.fileSize - b.fileSize,
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            width: 100,
            render: (category) => (
                categories.find(c => c.id === category)?.name || '未知'
            ),
            filters: categories.map(c => ({text: c.name, value: c.id})),
            onFilter: (value, record) => record.category === value,
        },
        {
            title: '上传时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
            width: 180,
            render: (time) => new Date(time).toLocaleString(),
            sorter: (a, b) => new Date(a.uploadTime) - new Date(b.uploadTime),
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined/>}
                        onClick={() => showDetail(record)}
                    >
                        详情
                    </Button>
                    <Button
                        type="link"
                        icon={<DownloadOutlined/>}
                        onClick={() => handleDownload(record.id)} // 传入种子ID
                    >
                        下载
                    </Button>
                </Space>
            ),
        }
    ];

    return (
        <div className="torrent-container">
            <Card
                title="种子列表"
                extra={
                    <Space>
                        <Button onClick={handleReset}>重置</Button>
                        <Button type="primary" onClick={handleSearch}>搜索</Button>
                    </Space>
                }
            >
                <div className="search-bar">
                    <Input
                        placeholder="输入种子ID精确搜索"
                        prefix={<SearchOutlined/>}
                        value={searchParams.id}
                        onChange={(e) => setSearchParams({...searchParams, id: e.target.value})}
                        style={{width: 200, marginRight: 16}}
                    />
                    <Select
                        placeholder="选择分类"
                        style={{width: 120}}
                        allowClear
                        value={searchParams.category}
                        onChange={(value) => setSearchParams({...searchParams, category: value})}
                    >
                        {categories.map(category => (
                            <Option key={category.id} value={category.id}>{category.name}</Option>
                        ))}
                    </Select>
                </div>

                <Table
                    columns={columns}
                    dataSource={data.list}
                    rowKey="id"
                    loading={loading}
                    pagination={false}
                />

                <div style={{marginTop: 16, textAlign: 'right'}}>
                    <Pagination
                        current={searchParams.page}
                        pageSize={searchParams.size}
                        total={data.total}
                        onChange={handlePageChange}
                        showSizeChanger
                        showQuickJumper
                        showTotal={total => `共 ${total} 条`}
                    />
                </div>
            </Card>

            {/* 详情模态框 */}
            <Modal
                title="种子详情"
                width={800}
                visible={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={[
                    <Button
                        key="download"
                        type="primary"
                        icon={<DownloadOutlined/>}
                        onClick={() => selectedTorrent && handleDownload(selectedTorrent.id)}
                    >
                        下载种子
                    </Button>,
                    <Button key="close" onClick={() => setIsModalVisible(false)}>
                        关闭
                    </Button>
                ]}
            >
                {selectedTorrent && (
                    <>
                        <Descriptions bordered column={2}>
                            <Descriptions.Item label="标题" span={2}>
                                {selectedTorrent.title}
                                {selectedTorrent.freeleech && (
                                    <Tag color="green" style={{marginLeft: 8}}>免费</Tag>
                                )}
                            </Descriptions.Item>
                            <Descriptions.Item label="描述">{selectedTorrent.description}</Descriptions.Item>
                            <Descriptions.Item label="IMDb链接">
                                {selectedTorrent.imdbLink ? (
                                    <a href={selectedTorrent.imdbLink} target="_blank" rel="noreferrer">
                                        {selectedTorrent.imdbLink}
                                    </a>
                                ) : '无'}
                            </Descriptions.Item>
                            <Descriptions.Item
                                label="文件大小">{formatSize(selectedTorrent.fileSize)}</Descriptions.Item>
                            <Descriptions.Item label="文件数量">{selectedTorrent.fileCount}</Descriptions.Item>
                            <Descriptions.Item label="分类">
                                {categories.find(c => c.id === selectedTorrent.category)?.name || '未知'}
                            </Descriptions.Item>
                            <Descriptions.Item label="语言">{selectedTorrent.language || '无'}</Descriptions.Item>
                            <Descriptions.Item
                                label="字幕信息">{selectedTorrent.subtitleInfo || '无'}</Descriptions.Item>
                            <Descriptions.Item label="上传时间">
                                {new Date(selectedTorrent.uploadTime).toLocaleString()}
                            </Descriptions.Item>
                            <Descriptions.Item label="促销状态">
                                <Tag color="orange">{selectedTorrent.promotionStatus}</Tag>
                                <div style={{marginTop: 8}}>
                                    <Progress
                                        percent={selectedTorrent.uploadMultiplier * 50}
                                        format={() => `${selectedTorrent.uploadMultiplier}X上传`}
                                        status="active"
                                    />
                                    <Progress
                                        percent={selectedTorrent.downloadDiscount === '100%' ? 100 : 50}
                                        format={() => `${selectedTorrent.downloadDiscount}下载`}
                                        status="active"
                                    />
                                </div>
                            </Descriptions.Item>
                            <Descriptions.Item label="InfoHash" span={2}>
                                <code>{selectedTorrent.infoHash}</code>
                            </Descriptions.Item>
                        </Descriptions>

                        {!selectedTorrent.anonymous && selectedTorrent.uploaderId && (
                            <>
                                <Divider orientation="left">上传者信息</Divider>
                                <Card loading={uploaderLoading}>
                                    {uploaderInfo && (
                                        <div className="uploader-info">
                                            <div className="uploader-avatar">
                                                <Avatar
                                                    size={64}
                                                    src={uploaderInfo.avatar}
                                                    icon={<UserOutlined/>}
                                                />
                                                {uploaderInfo.userId !== currentUserId && (
                                                    <Button
                                                        type="text"
                                                        icon={uploaderInfo.followed ? <StarFilled/> : <StarOutlined/>}
                                                        onClick={() => handleFollow(uploaderInfo.userId, uploaderInfo.followed)}
                                                    >
                                                        {uploaderInfo.followed ? '已关注' : '关注'}
                                                    </Button>
                                                )}
                                            </div>
                                            <div className="uploader-details">
                                                <h3>{uploaderInfo.username}</h3>
                                                <p>等级: Lv.{uploaderInfo.level}</p>
                                                <p>注册日期: {uploaderInfo.registrationDate}</p>
                                                <p>上传量: {formatSize(uploaderInfo.uploadedDelta * 1024 * 1024 * 1024)}</p>
                                            </div>
                                        </div>
                                    )}
                                </Card>
                            </>
                        )}

                        {/* 评论区 */}
                        <Divider orientation="left">
                            评论区 <Tag color="blue">{commentList.total} 条评论</Tag>
                        </Divider>

                        {/* 评论输入框 */}
                        <Card className="comment-input-card">
                            <Form.Item>
                                <TextArea // 修正为 TextArea
                                    rows={4}
                                    placeholder="分享你的观点..."
                                    value={commentContent}
                                    onChange={(e) => setCommentContent(e.target.value)}
                                    onPressEnter={handleCommentSubmit}
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button
                                    type="primary"
                                    onClick={handleCommentSubmit}
                                    disabled={!commentContent.trim()}
                                    icon={<CommentOutlined/>}
                                >
                                    发表评论
                                </Button>
                            </Form.Item>
                        </Card>

                        {/* 评论列表（使用 List.Item 自定义渲染） */}
                        <List
                            className="comment-list"
                            itemLayout="horizontal"
                            dataSource={commentList.list}
                            loading={commentLoading}
                            renderItem={(item) => (
                                <List.Item>
                                    <List.Item.Meta
                                        avatar={<Avatar
                                            src={item.avatar || 'https://gw.alipayobjects.com/zos/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'} // 示例头像
                                            alt={item.username}
                                            icon={<UserOutlined/>}
                                        />}
                                        title={<span>{item.username || '匿名用户'}</span>}
                                        description={
                                            <>
                                                <p>{item.content}</p>
                                            </>
                                        }
                                    />
                                    <div>
                                        <span>{new Date(item.createTime).toLocaleString()}</span>
                                        <Space>
                                            <span onClick={() => handleLikeComment(item.id)}>
                                                <LikeOutlined/> {item.likes || 0}
                                            </span>
                                            {currentUserId && currentUserId === String(item.userId) && (
                                                <span onClick={() => handleDeleteComment(item.id)}
                                                      style={{color: '#ff4d4f'}}>
                                                    <DeleteOutlined/> 删除
                                                </span>
                                            )}
                                        </Space>
                                    </div>
                                </List.Item>
                            )}
                        />

                        {/* 评论分页 */}
                        <div style={{marginTop: 16, textAlign: 'right'}}>
                            <Pagination
                                current={commentPage}
                                pageSize={5}
                                total={commentList.total}
                                onChange={handleCommentPageChange}
                                showQuickJumper
                                showTotal={total => `共 ${total} 条评论`}
                            />
                        </div>
                    </>
                )}
            </Modal>
        </div>
    );
};

export default TorrentList;